import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:get/get.dart';
import 'package:yysk_app/pages/nft_pages/wallet_pages/enterprise_auth_zhifu/title_top_widget.dart';
import 'package:yysk_app/pages/nft_pages/wallet_pages/enterprise_auth_zhifu/title_top_widget2.dart';
import 'package:yysk_app/utils/colors.dart';
import 'package:yysk_app/utils/helper.dart';
import 'package:oktoast/oktoast.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:url_launcher/url_launcher.dart';

import '../../my_points/points_page.dart';
import '../../pay_pages/result_payment/result_payment_page.dart';
import '../../pay_pages/result_payment/result_payment_zhifu_page.dart';
import '../../setting/modify_password.dart';
import '../../setting/setting_exchange_psw.dart';
import '../wallet/wallet_page.dart';
import 'WebViewExample.dart';


class MyWebViewZhifuPayPage extends StatefulWidget {
  const MyWebViewZhifuPayPage({super.key});
  static const path = '/webViewZhifuPay';

  @override
  State<MyWebViewZhifuPayPage> createState() => _MyWebViewPageState();
}

class _MyWebViewPageState extends State<MyWebViewZhifuPayPage> {
  // late WebViewController _controller;
  final RxDouble _progress = 0.0.obs;
  late var url = '';
  late var outTradeNo;
  @override
  void initState() {
    super.initState();
    _checkPermissions();
    try {

      final params = Get.parameters ?? {};
      final args = Get.arguments ?? {};
      var getUrl = params['url'] ?? args['url'];
      outTradeNo = params['outTradeNo'] ?? args['outTradeNo'];

      if (getUrl != null) {
        url = Uri.decodeComponent(getUrl);
        // print('$getUrl ==== getUrl');
      } else {
        Get.back();
        Get.snackbar('错误', 'URL 无效');
      }
    } catch (e) {
      debugPrint('解析 URL 失败: $e');
      Get.back();
      Get.snackbar('错误', 'URL 格式不正确');
    }
  }

  InAppWebViewController? webViewController;
  // 在 _MyWebViewPageState 类中
  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        Get.offNamed(
          '${ResultPaymentZhifuPage.path}?buyNow=1&outTradeNo=${outTradeNo}',
          arguments: {
            'buyNow': '1',
            "outTradeNo": outTradeNo,
          },
        );
        return true; // 允许关闭当前页面1
      },
      
      child: SafeArea(top: true,bottom: false,child: Scaffold(
        resizeToAvoidBottomInset: false,
        body: Column(
          children: [
            TitleTopWidget2(title:"",titleColor: AppColors.fontColorBlack,
              onLeftPressed: () {
                Get.offNamed(
                  '${ResultPaymentZhifuPage.path}?buyNow=1&outTradeNo=${outTradeNo}',
                  arguments: {
                    'buyNow': '1',
                    "outTradeNo": outTradeNo,
                  },
                );
              },
            ),
            Container(
              width: context.width,
              height: 10.px,
              color: AppColors.backgroundColor,
            ),
            // hiSpace(height: 10.px,width: context.width),
            _buildProgressBar(),
            Expanded(child:_buildWebView())

          ],
        ),
      )),
    );
  }
  Widget _buildWebView() {
    // return InAppWebView(
    //   initialUrlRequest: URLRequest(url: WebUri(url)),
    //   initialOptions: InAppWebViewGroupOptions(
    //     crossPlatform: InAppWebViewOptions(
    //       mediaPlaybackRequiresUserGesture: false,
    //       javaScriptEnabled: true,
    //       javaScriptCanOpenWindowsAutomatically: true,
    //       useShouldOverrideUrlLoading: true, // 使用shouldOverrideUrlLoading事件
    //     ),
    //     android: AndroidInAppWebViewOptions(
    //       useHybridComposition: true,
    //       allowFileAccess: true,
    //       useShouldInterceptRequest: true,
    //     ),
    //     ios: IOSInAppWebViewOptions(
    //         allowsInlineMediaPlayback: true,
    //         isFraudulentWebsiteWarningEnabled: false),
    //   ),
    //   onWebViewCreated: (controller) {
    //     webViewController = controller;
    //   },
    //   onPermissionRequest: (controller, request) async {
    //     // 处理网页内的权限请求
    //     return PermissionResponse(
    //       resources: request.resources,
    //       action: PermissionResponseAction.GRANT,
    //     );
    //   },
    //   onProgressChanged: (controller, progress) {
    //     _progress.value = progress / 100;
    //   },
    //   onLoadStart: (controller, url) {
    //     // 确认控制器已非null再使用
    //     if (controller == null) {
    //       return ;
    //     }
    //   },
    //   shouldOverrideUrlLoading: (controller, navigationAction) async {
    //     try {
    //       String uri = navigationAction.request.url!.rawValue.toString();
    //       if(uri.contains("https://www.baidu.com/")){
    //         Get.offNamed(
    //           '${ResultPaymentZhifuPage.path}?buyNow=1&outTradeNo=${outTradeNo}',
    //           arguments: {
    //             'buyNow': '1',
    //             "outTradeNo": outTradeNo,
    //           },
    //         );
    //       }
    //     } catch (e) {
    //       debugPrint('解析 URL 错误: $e');
    //     }
    //   },
    // );
    return WebViewExample(url: url, outTradeNo: outTradeNo);
  }

  Widget _buildProgressBar() {
    return LinearProgressIndicator(
      minHeight: 1.px,
      color: const Color(0xFFFFFFFF),
      value: _progress.value,
    );
  }
  Future<void> _checkPermissions() async {
    // 请求摄像头和麦克风权限
    final status = await [Permission.camera, Permission.microphone].request();

    if (status[Permission.camera]!.isGranted &&
        status[Permission.microphone]!.isGranted) {
    } else {
      Get.snackbar('权限被拒绝', '请前往设置开启权限');
    }
  }
}
